package cn.gdrj.est.service.impl;

import cn.gdrj.est.constants.Constants;
import cn.gdrj.est.service.SmsVerifyCodeService;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class SmsVerifyCodeServiceImpl implements SmsVerifyCodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void sendVerifyCode(String phone, Integer codeType) {

        if (Constants.Sms.TYPE_REGIST_OR_LOGIN.equals(codeType)) {
            sendLoginVerifyCode(phone);
        } else if (Constants.Sms.TYPE_UP_PASS.equals(codeType)) {
            sendUpdateVerifyCode(phone);
        } else if (Constants.Sms.TYPE_NOTICE.equals(codeType)) {
            sendNoticeVerifyCode(phone);
        }
    }

    @Override
    public String getLoginVerifyCode(String phone) {
        String redisSmsKey= getRedisSmsKey(phone);
        String verifyCode = redisTemplate.opsForValue().get(redisSmsKey);
        return verifyCode;
    }

    @Override
    public void removeLoginVerifyCode(String phone) {
        String redisSmsKey= getRedisSmsKey(phone);
        redisTemplate.delete(redisSmsKey);
    }

    private String getRedisSmsKey(String phone){
        return Constants.Redis.PREFIX_SMS+phone;
    }

    private void sendLoginVerifyCode(String phone) {
        // 根据手机号获取验证码
        String verifyCode = getLoginVerifyCode(phone);

        // 如果获取值不为空，直接返回
        if(!Objects.isNull(verifyCode)){
            return;
        }

        // 生成6位随机的验证码
        verifyCode = RandomUtil.randomNumbers(6);

        // 发送短信
        Map<String,Object> data= new HashMap<>();
        data.put("code",verifyCode);
        try {
            SendSmsResponseBody smsResponseBody =
                    sendSms(phone, "SMS_192541436", data);
            // 缓存存到redis
            String redisSmsKey = getRedisSmsKey(phone);
            redisTemplate.opsForValue()
                    .set(redisSmsKey,verifyCode,5, TimeUnit.MINUTES);
            // 保存日志
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendNoticeVerifyCode(String phone) {
    }

    private void sendUpdateVerifyCode(String phone) {
        
    }

    private SendSmsResponseBody sendSms(String phone,
                                        String templateCode,
                                        Map<String,Object> data) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId("LTAI5tRMVamGTM4EsvdXdSat")
                // 您的AccessKey Secret
                .setAccessKeySecret("OaPKUeJcaN2ETa2FqSRxseP5Qylt7n");
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = new Client(config);


        String templateParam = JSON.toJSONString(data);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("金码二手兔")
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam);


        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        return sendSmsResponse.getBody();
    }
}
